package com.goddess.yeecolor.webview;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.goddess.yeecolor.R;
import com.goddess.yeecolor.activity.ReusingRaymentActivity;
import com.goddess.yeecolor.base.BaseActivity;
import com.goddess.yeecolor.tools.CookieUtils;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.Item_ExerciseItemButtom;
import com.goddess.yeecolor.view.PopPopuWindowUtils;
import com.goddess.yeecolor.view.dialog_progress;
import com.goddess.yeecolor.view.sharePopuWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sharesdk.framework.ShareSDK;

/**
 * 作者: CaoJunping
 * 时间: 2017/1/13
 * 作用: ******
 * 备注: 学院的优雅公开课 的webview页面
 */
public class BoutiqueFragmentViewpagerWebView extends BaseActivity {
    @InjectView(R.id.title_back)
    ImageView titleBack;
    @InjectView(R.id.title_text)
    TextView titleText;
    private WebView webView;
    private ImageView img;
    private String id;
    private String price;//上个页面传过来的webview的地址,用户标示,课程ID ,课程价格
    private Map<Object, Object> map;
    private View view;
    private String webviewString;
    private dialog_progress dialog_progress;
    Intent intent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(this).inflate(R.layout.boutique_fragment_web_view, null);
        setContentView(view);
        ShareSDK.initSDK(this);
        ButterKnife.inject(this);
        initFindView();
        initData();
        initOnClck();
    }

    @Override
    public void initOnClck() {
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setBottomButton();
    }

    @Override
    public void initFindView() {
        webView = (WebView) findViewById(R.id.public_webview);
        img = (ImageView) findViewById(R.id.title_back);
    }

    @Override
    public void initData() {
        intent = getIntent();
        id = intent.getStringExtra("id");
        price = intent.getStringExtra("price");
        String url = MyUrl.SHOW;
        map = new HashMap<>();
        map.put("course_id", id + "");
        map.put("unique", SharePreceUtils.getOther("user", "unique"));
        OkttpUtils.getIntence().OkttpPost(url, map, handler, 1);
        setProgress();
      //  CookieUtils.getInstence().webViewStart(BoutiqueFragmentViewpagerWebView.this, webView,titleText,webviewString);
        titleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.goBack();
            }
        });
    }

    private void setProgress() {
        dialog_progress = new dialog_progress(BoutiqueFragmentViewpagerWebView.this);
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }


    /**
     * 底部分享 收藏 购买
     */
    private sharePopuWindow share;
    private PopPopuWindowUtils popuWindowUtils;

    public void setBottomButton() {
        /**
         * 分享
         */
        share=new sharePopuWindow(this,MyUrl.TYPEC,id+"");
        Item_ExerciseItemButtom.initShare(view, (view) -> {
                    share.showAsDropDown(img, Gravity.CENTER, 0, 0);
                }
        );

        /**
         * 收藏
         */
        Item_ExerciseItemButtom.initCollect(view, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }, islike);

        Item_ExerciseItemButtom.textCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (islike == 0) {
                    map = new HashMap<Object, Object>();
                    map.put("id", id + "");
                    map.put("unique", SharePreceUtils.getOther("user", "unique"));
                    map.put("typed", MyUrl.TYPEC);
                    OkttpUtils.getIntence().OkttpPost(MyUrl.COLLECT, map, handler, 2);
                } else if (islike == 1) {
                    map = new HashMap<Object, Object>();
                    map.put("id", id + "");
                    map.put("unique", SharePreceUtils.getOther("user", "unique"));
                    map.put("typed", MyUrl.TYPEC);
                    OkttpUtils.getIntence().OkttpPost(MyUrl.COLLECT, map, handler, 2);
                }
            }
        });



        /*
         * 购买
         */

        OnClickLintener onClickLintener = new OnClickLintener();
        //弹窗
        popuWindowUtils = new PopPopuWindowUtils(this, onClickLintener, "查看报名凭证", "取消报名", isapply);


        Item_ExerciseItemButtom.initBuy(view, isapply, Double.valueOf(price));
        Item_ExerciseItemButtom.buyLinear.setOnClickListener((view1) -> {
            if (isapply == 1) {//我已报名
                /**
                 * 取消报名
                 */
                popuWindowUtils.popuwindow_cancalenroll.setOnClickListener((view) -> {
                    map = new HashMap<Object, Object>();
                    map.put("order_id", order_id + "");//购买order_id
                    map.put("unique", SharePreceUtils.getOther("user", "unique"));
                    OkttpUtils.getIntence().OkttpPost(MyUrl.CALCALBUY, map, handler, 3);
                });
//                /**
//                 * 查看凭证
//                 */
//                popuWindowUtils.popuwindow_examine.setOnClickListener((view)->{
//                    map=new HashMap<Object, Object>();
//                    map.put("state",state+"");//购买order_id
//                    map.put("unique", SharePreceUtils.getOther("user","unique"));
//                    OkttpUtils.getIntence().OkttpPost(MyUrl.BUYLIST,map,handler,1);
//                });
            } else if (isapply == 0) {//购买

                map = new HashMap<Object, Object>();
                map.put("buy_id", id + "");//购买id
                map.put("unique", SharePreceUtils.getOther("user", "unique"));
                map.put("typed", MyUrl.TYPEC);
                OkttpUtils.getIntence().OkttpPost(MyUrl.BUY, map, handler, 3);

            }
//            else if (isapply==2){
//
//            }
        });
    }

    /**
     * popuwindow的弹框
     */
    class OnClickLintener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
        }
    }

    private int islike, isapply, buy_id;//有没有收藏,有没有购买,
    private String order_id;//订单号
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String jsonString = msg.getData().getString("result");
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                int code = jsonObject.getInt("code");
                if (code == 100) {
                    JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                    if (msg.what == 1) {
                        JSONObject jsonObject2 = jsonObject1.getJSONObject("operation");
                        islike = jsonObject2.getInt("islike");
                        isapply = jsonObject2.getInt("isapply");
                        JSONObject jsonObject3=jsonObject1.getJSONObject("wen_token");
                        String token=jsonObject3.getString("token");
                        if (isapply == 0) {
                            String fileUrl = "file:///android_asset/needpay.html";
                            webView.getSettings().setDefaultTextEncodingName("utf-8");
                            webView.loadUrl(fileUrl);
                            webView.setWebViewClient(new WebViewClient());
                        } else if (isapply == 1) {
                            if(!token.equals("")){
                                webviewString = intent.getStringExtra("webview");
                                CookieUtils.getInstence().webViewStart(BoutiqueFragmentViewpagerWebView.this, webView,titleText, webviewString,token);
                            }

                        }
                        if (dialog_progress != null && dialog_progress.isShowing()) {
                            dialog_progress.dismiss();
                        }
                        setBottomButton();
                        Item_ExerciseItemButtom.initCollect(view, (view1) -> {

                        }, islike);
                    } else if (msg.what == 2) {
                        if (islike == 0) {
                            ToastUtils.setToast(jsonObject.getString("msg"), R.mipmap.activebottomlike3x, BoutiqueFragmentViewpagerWebView.this);
                            Item_ExerciseItemButtom.initCollect(view, (view1) -> {
                            }, 1);
                            islike = 1;
                        } else {
                            ToastUtils.setToast(jsonObject.getString("msg"), R.mipmap.collect, BoutiqueFragmentViewpagerWebView.this);
                            Item_ExerciseItemButtom.initCollect(view, (view1) -> {
                            }, 0);
                            islike = 0;
                        }
                    } else if (msg.what == 3) {

                        JSONObject result = jsonObject.getJSONObject("result");
                        ToastUtils.setToastText(jsonObject.getString("extends"), BoutiqueFragmentViewpagerWebView.this);
                        JSONObject events = result.getJSONObject("events");
                        int id = result.getInt("id");
                        buy_id = result.getInt("buy_id");
                        String typed = result.getString("typed");
                        order_id = result.getString("order_id");
                        SharePreceUtils.saveOrder(order_id, events.getString("title"), result.getString("price"));
                        Bundle bundle = new Bundle();
                        bundle.putString("order_id", order_id);
                        bundle.putString("title", events.getString("title"));
                        bundle.putString("price", result.getString("price"));
                        bundle.putString("thumb", events.getString("thumb"));
                        bundle.putString("typed", typed);
                        JumpIntents.startIntent(BoutiqueFragmentViewpagerWebView.this, ReusingRaymentActivity.class, bundle);//跳转到支付界面
                    }
                }

                if (dialog_progress != null && dialog_progress.isShowing()) {
                    dialog_progress.dismiss();
                }
            } catch (JSONException e) {

            }
        }
    };
}
